const util = Editor.require("packages://gif-to-animation/utils/gif-util.js");
let fs = require('fire-fs');
let path = require('fire-path');

Editor.Panel.extend({
    style: fs.readFileSync(Editor.url('packages://gif-to-animation/panel/index.css'), 'utf-8'),

    template: `
    <div class="total_area">
    <br>
    <br>
    <a href="javascript:;" class="a-upload">
        <input type="file" class="" name="选择gif文件" id="input_file" accept=".gif"/>选择文件
    </a>
    <ui-input id="input_path"> </ui-input>
    <br>
    <br>
    <hr />
    <ui-checkbox id="check_removebg" style= "margin-left: 5px;">底图变透明</ui-checkbox>
    <br>
    <h3>底图颜色</h3> 
    <ui-color id="color1" value="#fff"></ui-color>
    <br>
    <h3>底图去除偏差(偏差计算方式为rgb像素平方差的根)</h3> 
    <ui-slider id="slider1" min="0" max="255" step="1" value="0"></ui-slider>
    <br>
    <hr />
    <ui-button id="btn_run">开始转换</ui-button>
    <hr />
    <br>
    <div>生成的动画资源目录在项目的resources/gif-to-animation</div>
    <div>--如果您在使用中有什么意见或建议,请联系qq：1101502561</div>
    </div>
  `,

    $: {
        input_file: '#input_file',
        input_path: '#input_path',
        btn_run: '#btn_run',
        check_removebg: '#check_removebg',
        color1: "#color1",
        slider1:'#slider1',
    },

    ready () {
        console.log('panel is ready');
        this.colorArr = [255,255,255];
        this.$input_file.addEventListener('change', function (event) {
            var file = event.currentTarget.files[0];
            this.selectFinish(file);
        }.bind(this));
        this.$btn_run.addEventListener('confirm', function () {
            this.doRunWork();
        }.bind(this));
        this.$slider1.addEventListener('confirm', function (event) {
            this.onSliderConfirm(event);
        }.bind(this));
        this.$color1.addEventListener('confirm', function (event) {
            this.onColorConfirm(event);
        }.bind(this));
    },

    onSliderConfirm: function (event) {
        this.$slider1.value = parseInt(this.$slider1.value);
    },

    onColorConfirm: function (event) {
        // this.$slider1.value = parseInt(this.$slider1.value);
        this.colorArr = this.$color1.value;
    },

    selectFinish: function (file) {
        console.log('selectFinish path:' + file);
        this.selectFile = file;
        this.$input_path.value = file.name;
    },

    doRunWork: function () {
        var file = this.selectFile;
        util.tolerance = this.$slider1.value;
        util.bgColor = this.colorArr;

        if (this.selectFile == null) {
            Editor.Dialog.messageBox({
                title: "提示",
                message: "请先选中一个gif文件",
                buttons: ["确定"],
                defaultId: 0,
                cancelId: 1,
                noLink: true
            });
            return;
        }
        var tmpDir = Editor.url('packages://gif-to-animation/temp');
        util._isRemoveBg = this.$check_removebg.checked;
        //如果存在上次操作的缓存就先把缓存清楚
        if (fs.existsSync(tmpDir) === false) {
            fs.mkdirSync(tmpDir);
        } else {
            var files = fs.readdirSync(tmpDir);
            files.forEach(function(file) {
                var stats = fs.statSync(tmpDir+'/'+file);
                if(stats.isDirectory() === false) {
                    fs.unlinkSync(tmpDir+'/'+file);
                }
            });
        }
        util.parseGif(file, tmpDir, function (error, gif_name, dalayTime, list) {
            this.onParseGifFinish(error, gif_name, dalayTime, list);
        }.bind(this));
    },

    onParseGifFinish: function (error, gif_name, delayTime, list) {
        if (error) {
            Editor.log(error);
            return;
        }
        let names = [];
        let files = [];
        for (let i = 0; i < list.length; i++) {
            names[i] = list[i].name;
            files[i] = list[i].fullpath;
        }
        this._names = names;
        this._delayTime = delayTime;
        this.copyPngFileToResources(files, gif_name);
    },

    copyPngFileToResources: function (list, gif_name) {
        var dest = 'db://assets/resources/gif-to-animation';
        var destUrl = Editor.url(dest);
        let self = this;
        if (fs.existsSync(destUrl) === false) {
            fs.mkdirSync(destUrl);
            Editor.assetdb.refresh(dest, function () {
                Editor.assetdb.import(list, dest, true, function ( err, results) {
                    if (err) {
                        Editor.log(err);
                    }
                    self.makeAnimation(results, gif_name);
                });
            });
        } else {
            Editor.assetdb.import(list, dest, true, function (err, results) {
                if (err) {
                    Editor.log(err);
                }
                self.makeAnimation(results, gif_name);
            });
        }
    },

    makeAnimation: function (results, gif_name) {
        let spriteFrameUuids = [];
        for (let i = 0; i < this._names.length; i++) {
            let name = this._names[i];
            let uuidPath = 'assets/resources/gif-to-animation/' + name;
            for (let j = 0; j < results.length; j++) {
                let item = results[j];
                if (item.type === 'sprite-frame' && (item.url.indexOf(uuidPath) !== -1) ) {
                    spriteFrameUuids.push(item.uuid);
                    break;
                }
            }
        }
        if (spriteFrameUuids.length !== this._names.length) {
            Editor.warn('[gif-to-animation][makeAnimation] 有关键帧丢失');
        }

        //生成anim文件json数据
        let animation = {};
        animation['__type__'] = "cc.AnimationClip";
        animation['_name'] = "ani_" + gif_name;
        animation['_objFlags'] = 0;
        animation['_native'] = "";
        let frameCount = 3;
        if (this._delayTime != 0) {
            frameCount = parseInt(60 / (1 / (this._delayTime * 0.01)));
        }
        let frameTime = 1 / 60 * frameCount;
        animation['_duration'] = spriteFrameUuids.length * frameTime;    //动画时长
        animation['sample'] = 60;                       //帧率
        animation['speed'] = 1;                         //速度
        animation['wrapMode'] = 2;                      //循环播放
        animation['curveData'] = this.getFrameAnimationData(spriteFrameUuids, frameTime);
        animation['events'] = [];
        let str = JSON.stringify(animation, null, 4);
        let anim_file_name = 'db://assets/resources/gif-to-animation/ani_' + gif_name + '.anim';
        Editor.assetdb.create(anim_file_name, str, function (err, results) {
            results.forEach(function ( result ) {
                // result.uuid
                // result.parentUuid
                // result.url
                // result.path
                // result.type
            });
        });
    },

    getFrameAnimationData: function (uuids, frameTime) {
        let spriteFrame = [];
        let cc_sprite = {};
        let comps = {};
        let curveData = {};
        cc_sprite['spriteFrame'] = spriteFrame;
        comps['cc.Sprite'] = cc_sprite;
        curveData['comps'] = comps;
        for (let i = 0; i < uuids.length; i++) {
            let item = {};
            item.frame = frameTime * i;
            item.value = {};
            item.value['__uuid__'] = uuids[i];
            spriteFrame.push(item);
        }
        return curveData;
    },

    messages: {
        'scene:enter-prefab-edit-mode': function (event, uuid) {
            //do some work
            util.enterPrefabEditModeCallback(uuid);
        },
    }
});